/*
 * FileName：MailUtil.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.common.util;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Create by yster@foxmail.com 2018/5/28/028 21:05
 */
public class MailUtil {

    private static JavaMailSenderImpl javaMailSender;

    // 获取send
    public static JavaMailSenderImpl getMailSender() {
        if (javaMailSender == null) {
            synchronized (MailUtil.class) {
                if (javaMailSender == null) {
                    javaMailSender = new JavaMailSenderImpl();
                    javaMailSender.setHost(PropertiesUtil.getString("mail.host"));
                    javaMailSender.setPort(PropertiesUtil.getInt("mail.port"));
                    javaMailSender.setUsername(PropertiesUtil.getString("mail.username"));
                    javaMailSender.setPassword(PropertiesUtil.getString("mail.password"));
                    javaMailSender.setDefaultEncoding("utf-8");
                    Properties p = new Properties();
                    p.setProperty("mail.smtp.timeout", PropertiesUtil.getString("mail.timeout"));
                    p.setProperty("mail.smtp.auth", "false");
                    javaMailSender.setJavaMailProperties(p);
                }
            }
        }
        return javaMailSender;
    }

    /**
     * 发送邮件
     *
     * @param to      接受人
     * @param subject 主题
     * @param html    发送内容
     * @throws MessagingException           异常
     * @throws UnsupportedEncodingException 异常
     */
    public static void sendMail(String to, String subject, String html) throws MessagingException {
        MimeMessage mimeMessage = getMailSender().createMimeMessage();
        // 设置utf-8或GBK编码，否则邮件会有乱码
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(PropertiesUtil.getString("mail.from"));
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        getMailSender().send(mimeMessage);
    }
}
